package com.chuangdun.flutter.plugin.alarm

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.VibrationEffect
import android.os.Vibrator
import android.os.VibratorManager
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import android.view.animation.AnimationUtils
import android.widget.Button
import android.widget.TextView

/**
 * 用于显示闹钟提醒对话框的Activity
 * 这个Activity会在桌面弹出提醒对话框，当应用在前台时使用
 * 样式参考iOS UIAlertController
 */
class AlarmDialogActivity : Activity() {

    private var mediaPlayer: MediaPlayer? = null
    private var dialog: AlertDialog? = null
    private var vibrator: Vibrator? = null
    private var isVibrating = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置Activity能够在锁屏和后台显示
        setupWindowFlags()

        // 初始化震动器
        initializeVibrator()

        // 获取传递的数据
        val title = intent.getStringExtra("title") ?: "提醒"
        val body = intent.getStringExtra("body") ?: "您有一个提醒"
        //val isRepeating = intent.getBooleanExtra("isRepeating", false)

        // 播放提醒音
        playAlarmSound()

        // 创建并显示对话框
        showAlarmDialog(title, body)
    }

    private fun setupWindowFlags() {
        val window = window

        // 设置Activity能够在锁屏上显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
            setTurnScreenOn(true)
        } else {
            @Suppress("DEPRECATION") window.addFlags(
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
                        WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
            )
        }

        // 添加其他必要的标志
        window.addFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or
                    WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
                    WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
        )
    }

    private fun showAlarmDialog(title: String, body: String) {
        // 使用自定义布局创建对话框
        val dialogView = LayoutInflater.from(this).inflate(R.layout.alarm_dialog_layout, null)

        // 获取布局中的视图组件
        val titleText = dialogView.findViewById<TextView>(R.id.title_text)
        val bodyText = dialogView.findViewById<TextView>(R.id.body_text)
        val confirmButton = dialogView.findViewById<Button>(R.id.confirm_button)

        // 设置文本内容
        titleText.text = title
        bodyText.text = body

        // 设置按钮点击事件
        confirmButton.setOnClickListener {
            stopAlarmSound()
            stopVibration()
            dialog?.dismiss()
            finish()
        }

        // 创建对话框
        dialog = AlertDialog.Builder(this, R.style.UIAlertControllerDialogTheme)
            .setView(dialogView)
            .setCancelable(false)
            .create()

        // 设置对话框属性以实现UIAlertController风格
        val window = dialog?.window
        window?.apply {
            setGravity(Gravity.CENTER)
            // 设置圆角背景
            setBackgroundDrawableResource(android.R.color.transparent)

            // 设置窗口动画
            setWindowAnimations(android.R.style.Animation_Dialog)
        }

        // 显示对话框
        dialog?.show()

        // 添加淡入动画效果
        dialogView.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in))
    }

    private fun playAlarmSound() {
        // 立即启动震动和铃声
        startVibration()

        try {
            // 使用自定义铃声或系统默认闹钟铃声
            val alarmUri = AlarmUtils.getAlarmSoundUri(this)

            if (alarmUri != null) {
                mediaPlayer = MediaPlayer().apply {
                    setDataSource(this@AlarmDialogActivity, alarmUri)
                    isLooping = true

                    // 设置错误监听器
                    setOnErrorListener { _, what, extra ->
                        Log.e(TAG, "MediaPlayer 播放错误: what=$what, extra=$extra")
                        false // 返回false让系统处理错误
                    }

                    // 设置准备完成监听器
                    setOnPreparedListener {
                        try {
                            start()
                            Log.d(TAG, "铃声播放成功")
                        } catch (e: Exception) {
                            Log.e(TAG, "启动MediaPlayer失败: ${e.message}")
                        }
                    }

                    prepareAsync() // 异步准备
                }
            } else {
                Log.w(TAG, "无法获取铃声URI")
            }

        } catch (e: Exception) {
            Log.e(TAG, "设置铃声播放失败: ${e.message}", e)
        }

        // 不再需要延迟检查播放状态，因为震动已经启动
    }

    private fun stopAlarmSound() {
        mediaPlayer?.apply {
            if (isPlaying) {
                stop()
            }
            release()
        }
        mediaPlayer = null
    }

    /**
     * 初始化震动器
     */
    private fun initializeVibrator() {
        try {
            vibrator = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                val vibratorManager =
                    getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as VibratorManager
                vibratorManager.defaultVibrator
            } else {
                @Suppress("DEPRECATION")
                getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
            }
            Log.d(TAG, "震动器初始化成功")
        } catch (e: Exception) {
            Log.e(TAG, "震动器初始化失败: ${e.message}", e)
        }
    }

    /**
     * 启动震动作为铃声播放失败时的备用方案
     */
    private fun startVibration() {
        if (isVibrating) {
            Log.d(TAG, "震动已在进行中，跳过重复启动")
            return
        }

        try {
            vibrator?.let { vib ->
                if (vib.hasVibrator()) {
                    // 创建震动模式：震动1秒，暂停1秒，循环播放直到用户点击确定按钮
                    val pattern = longArrayOf(0, 1000, 1000)

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        val vibrationEffect = VibrationEffect.createWaveform(pattern, 0) // 0表示循环
                        vib.vibrate(vibrationEffect)
                    } else {
                        @Suppress("DEPRECATION")
                        vib.vibrate(pattern, 0) // 0表示循环
                    }

                    isVibrating = true
                    Log.d(TAG, "震动备用提醒已启动")
                } else {
                    Log.w(TAG, "设备不支持震动功能")
                }
            } ?: Log.w(TAG, "震动器未初始化")
        } catch (e: Exception) {
            Log.e(TAG, "启动震动失败: ${e.message}", e)
        }
    }

    /**
     * 停止震动
     */
    private fun stopVibration() {
        if (isVibrating) {
            try {
                vibrator?.cancel()
                isVibrating = false
                Log.d(TAG, "震动已停止")
            } catch (e: Exception) {
                Log.e(TAG, "停止震动失败: ${e.message}", e)
            }
        }
    }

    override fun onDestroy() {
        // 确保对话框被dismiss
        dialog?.takeIf { it.isShowing }?.dismiss()
        stopAlarmSound()
        stopVibration()
        super.onDestroy()
    }
}